import axios from 'axios';

/**
 * Http net 对象
 * 调用 getInstance() 获取实例
 *
 * @class Http
 */
export class Http {
    
    /**
     * @description 单例变量声明
     * @private
     * @static
     * @type {Http}
     * @memberof Http
     */
    private static Http: Http;

    /**
     * @description 获取 Http 单例对象
     * @static
     * @return {*}  {Http}
     * @memberof Http
     */
    public static getInstance(): Http {
        if (!Http.Http) {
            Http.Http = new Http();
        }
        return this.Http;
    }

    /**
     * 私有构造，拒绝通过 new 创建对象
     * @memberof Http
     */
    private constructor() { }

    /**
     * @description 网络请求对象
     * @static
     * @return {*} 
     * @memberof Http
     */
    public static getHttp() {
        return axios;
    }

    /**
     * @description post请求
     * @param {string} url 请求路径
     * @param {*} [params={}] 请求参数
     * @param {*} [_config] 请求配置
     * @return {*} {Promise<any>}
     * @memberof Http
     */
    public post(url: string, params: any = {}, _config?: any): Promise<any> {
      return new Promise((resolve: any, reject: any) => {
            const config = {
              headers: { 'Content-Type': 'application/json;charset=UTF-8', Accept: 'application/json' },
            }
            if (_config) {
              Object.assign(config, _config);
            }
            axios.post(url, params, config).then((response: any) => {
              resolve(response);
            }).catch((response: any) => {
              reject(response);
            });
        });
    }

    /**
     * @description 获取
     * @param {string} url 请求路径
     * @param {*} [params={}] 参数
     * @param {*} [config] 请求配置
     * @return {*}  {Promise<any>}
     * @memberof Http
     */
    public get(url: string, params: any = {}, config: any = {}): Promise<any> {
      return new Promise((resolve: any, reject: any) => {
        axios.get(url, config).then((response: any) => {
          resolve(response);
        }).catch((response: any) => {
          reject(response);
        });
    });
    }
}
